package com.glsc.ngateway.opmanage.controller.other;


import com.glsc.ngateway.common.api.platform.dto.other.TradeSeatHistoryDto;
import com.glsc.ngateway.common.api.common.ex.Result;
import com.glsc.ngateway.opmanage.service.other.TradeSeatHistoryService;
import com.glsc.ngateway.common.api.common.utils.PageUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;

/**
 * @Author: libj
 * @Date: 2022/4/19
 * @Desc: 交易单元租用流水信息管理
 * 交易单元租用流水表与交易单元租用信息表的差异在于流水表记录交易单元的变更历史，一个交易单元号存在多条记录
 */
@RestController
@RequestMapping("/api/tradeseathistory")
@Api(value = "TradeSeatHistoryController", tags = {"交易单元租用流水信息管理"})
public class TradeSeatHistoryController {

    private static Logger logger = LoggerFactory.getLogger(TradeSeatHistoryController.class);

    @Resource
    private TradeSeatHistoryService tradeSeatHistoryService;

    @GetMapping("/listpage")
    @ApiOperation(value = "交易单元租用流水信息分页查询", notes = "交易单元租用流水信息分页查询")
    public Result<Page<TradeSeatHistoryDto>> listPage(@ApiParam(value = "交易单元号") @RequestParam(required = false) String tradeSeatCode,
                                                      @ApiParam(value = "市场") @RequestParam(required = false) String tradeSeatMarket,
                                                      @ApiParam(value = "申请部门") @RequestParam(required = false)  String applyDeptName,
                                                      @ApiParam(value = "使用机构名称") @RequestParam(required = false)  String useCompanyName,
                                                      @ApiParam(value = "交易单元性质 字典: am_trade_seat_use_type") @RequestParam(required = false) String useType,
                                                      @ApiParam(value = "页码从1开始") @RequestParam(required = false) Integer pageNo,
                                                      @ApiParam(value = "每页显示条数 默认10") @RequestParam(required = false) Integer pageSize) {
        Page<TradeSeatHistoryDto> page = tradeSeatHistoryService.findPage(tradeSeatCode, tradeSeatMarket, applyDeptName, useType,useCompanyName, PageUtil.initPageNo(pageNo), PageUtil.initPageSize(pageSize));
            return Result.successData(page);
    }

    @PostMapping("/create")
    @ApiOperation(value = "创建交易单元租用流水信息", notes = "创建交易单元租用流水信息")
    public Result save(@ApiParam(required = true, value = "交易单元租用流水信息") @RequestBody TradeSeatHistoryDto tradeSeatHistoryDto) {
        logger.info("创建交易单元租用流水信息：" + tradeSeatHistoryDto);
        try {
            tradeSeatHistoryService.save(tradeSeatHistoryDto);
            return Result.successData("创建成功");
        } catch (Exception e) {
            logger.error("创建交易单元租用流水信息失败" + e.getLocalizedMessage(), e);
            return Result.failData(e.getMessage());
        }
    }

    @PostMapping("/update")
    @ApiOperation(value = "更新交易单元租用流水信息", notes = "更新交易单元租用流水信息")
    public Result update(@ApiParam(required = true, value = "交易单元租用流水信息") @RequestBody TradeSeatHistoryDto tradeSeatHistoryDto) {
        logger.info("更新交易单元租用流水信息：" + tradeSeatHistoryDto);
        try{
            tradeSeatHistoryService.update(tradeSeatHistoryDto);
            return Result.successData("更新成功");
        } catch (Exception e) {
            logger.error("更新城市信息失败" + e.getLocalizedMessage(), e);
            return Result.failData(e.getMessage());
        }
    }

    @PostMapping("/end")
    @ApiOperation(value = "停用交易单元租用流水信息", notes = "停用交易单元租用流水信息")
    public Result updateCityInfoDeleted(@ApiParam(required = true, value = "交易单元租用流水信息") @RequestBody TradeSeatHistoryDto tradeSeatHistoryDto) {
        logger.info("停用交易单元租用流水信息，Id：" + tradeSeatHistoryDto.getTradeSeatId());
        try {
            tradeSeatHistoryService.updateStateEndByTradeSeatId(tradeSeatHistoryDto.getTradeSeatId());
            return Result.successData("更新停用交易单元租用流水信息成功");
        } catch (Exception e) {
            logger.error("停用交易单元租用流水信息" + e.getLocalizedMessage(), e);
            return Result.failData(e.getMessage());
        }
    }

    //此功能只是初始化使用，迁移后不要了
//    @PostMapping("/importtradeseathistory")
//    @ApiOperation(value = "批量导入交易单元租用流水信息Excel文件", notes = "批量导入交易单元租用流水信息Excel文件")
//    public Result<List<TradeSeatHistoryDto>> importTradeSeatHistoryExcel(MultipartFile file) throws IOException {
//        try{
//            String oFileName = file.getOriginalFilename();
//            logger.info("收到Excel批量交易单元租用流水信息数据文件:{}",file.getOriginalFilename());
//            if(file.isEmpty()) {
//                throw AmException.error("批量导入交易单元租用流水信息Excel文件为空");
//            }
//            String destFileName = Constant.PROD_DOC_ROOT_DIR + CommonUtils.getDateStr(new Date(), DictConstant.FORMAT_DATE_YYYYMMDD)
//                    + File.separator + UUID.randomUUID() + File.separator + oFileName;//增加uuid层，解决上传文件名重复问题
//            File destFile = new File(documentInfoService.getUploadRoot() + destFileName);
//            FileUtils.copyInputStreamToFile(file.getInputStream(), destFile);
//
//            TradeSeatHistoryReader tradeSeatHistoryReader = new TradeSeatHistoryReader();
//            EasyExcel.read(destFile, TradeSeatHistoryImportDto.class, tradeSeatHistoryReader).sheet("Sheet1").doRead();
//            List<TradeSeatHistoryImportDto> importData = tradeSeatHistoryReader.getTradeSeatHistoryImportDtoList();
//            logger.info("批量导入交易单元租用流水信息Excel文件中提供了{}条记录",importData.size());
//            List<TradeSeatHistory> tradeSeatHistoryList = new ArrayList<>();
//            if(CollectionUtil.isNotEmpty(importData)) {
//
//                //获取交易单元市场字典map
//                Map<String, String> tradeSeatMarketDictMap = CacheManager.getDictFromRedis(DictConstant.DICT_CODE_TRADE_SEAT_MARKET).getDictValues().stream().collect(
//                        Collectors.toMap(DictValue::getLabel,DictValue::getValue));
//                //获取交易单元类型字典map
//                Map<String, String> tradeSeatUseTypeDictMap = CacheManager.getDictFromRedis(DictConstant.DICT_CODE_TRADE_SEAT_USE_TYPE).getDictValues().stream().collect(
//                        Collectors.toMap(DictValue::getLabel,DictValue::getValue));
//                //获取交易单元状态字典map
//                Map<String, String> tradeSeatStateDictMap = CacheManager.getDictFromRedis(DictConstant.DICT_CODE_TRADE_SEAT_STATE).getDictValues().stream().collect(
//                        Collectors.toMap(DictValue::getLabel,DictValue::getValue));
//
//                String importKey = CommonUtils.getDateStr(new Date(), DictConstant.FORMAT_DATE_YYYYMMDD) + UUID.randomUUID();
//                importData.forEach(item->{
//                    TradeSeatHistory tradeSeatHistory = new TradeSeatHistory();
//                    BeanUtil.copyProperties(item,tradeSeatHistory);
//                    tradeSeatHistory.setImportKey(importKey);
//                    tradeSeatHistory.setTradeSeatMarket(tradeSeatMarketDictMap.get(tradeSeatHistory.getTradeSeatMarket()));
//                    tradeSeatHistory.setUseType(tradeSeatUseTypeDictMap.get(tradeSeatHistory.getUseType()));
//                    tradeSeatHistory.setState(tradeSeatStateDictMap.get(tradeSeatHistory.getState()));
//                    tradeSeatHistoryList.add(tradeSeatHistory);
//                });
//            }
//            tradeSeatHistoryService.saveTradeSeatHistoryList(tradeSeatHistoryList);
//            return Result.successData(tradeSeatHistoryList);
//        } catch (Exception e){
//            logger.error("批量导入交易单元租用流水信息Excel文件失败:" + e.getMessage());
//            return Result.failData("批量导入交易单元租用流水信息Excel文件失败:" + e.getMessage());
//        }
//    }

    @GetMapping("/download")
    @ApiOperation(value = "下载模板文件")
    public void download(HttpServletResponse response) throws UnsupportedEncodingException {
        //强制下载不打开
        response.setContentType("application/force-download");
        //使用URLEncoder来防止文件名乱码或者读取错误
        response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode("交易单元租用流水信息模板.xlsx", "UTF-8"));
        try (InputStream input = this.getClass().getResourceAsStream("/exceltemplates/trade_seat_history_template.xlsx")) {
            OutputStream output = response.getOutputStream();
            XSSFWorkbook workbook = new XSSFWorkbook(input);
            workbook.write(output);
            workbook.close();
        } catch (IOException e) {
            logger.error("Error", e);
        }
    }
}
